package thread.threadpool;

import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2021/5/19 23:47
 * @description
 */
public class Test04 {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            int i = new Random().nextInt(10);
            System.out.println(Thread.currentThread().getId() + "--" + System.currentTimeMillis() + "开始睡眠：" + i + "秒");
            try {
                TimeUnit.SECONDS.sleep(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };


        //创建线程池，是用自定义的线程工厂
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);//守护线程。主线程结束后会自动退出
                System.out.println("创建了线程：" + thread);
                return thread;
            }
        });

        for (int i = 0; i < 8; i++) {
            threadPoolExecutor.submit(runnable);
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
